package vtt.android.dapanhc.utils;

import java.util.Calendar;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class VttAlarmManager {
	
	/**
	 * start alarm schedule everyday at approximate specific hour
	 * @param context
	 * @param hour
	 * @param receiverClass
	 */
	public static void startAlarmEveryday(Context context, int hour, Class<?> receiverClass) {
		Log.d("VttAlarmManager", "VTT>>> startAlarm");
		AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
		Intent intent = new Intent(context, receiverClass);
		PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
		
		// Set the alarm to start at 1 a.m.
		Calendar calendar = Calendar.getInstance();
		calendar.setTimeInMillis(System.currentTimeMillis());
		calendar.set(Calendar.HOUR_OF_DAY, hour);
		// alarm after 1 day
		am.setInexactRepeating(AlarmManager.RTC, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pi);
	}
	
	/**
	 * replace alarm schedule everyday at approximate specific hour
	 * @param context
	 * @param hour
	 * @param receiverClass
	 */
	public static void replaceAlarm(Context context, int hour, Class<?> receiverClass) {
		Log.d("VttAlarmManager", "VTT>>> replaceAlarm");
		AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
		Intent intent = new Intent(context, receiverClass);
		PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
		
		// Set the alarm to start with specific hour.
		Calendar calendar = Calendar.getInstance();
		calendar.setTimeInMillis(System.currentTimeMillis());
		calendar.set(Calendar.HOUR_OF_DAY, hour);
		
		am.cancel(pi);
		//pi.cancel();
		// alarm after 1 day
		am.setInexactRepeating(AlarmManager.RTC, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pi);
	}
}
